package com.ptswitch.material.pages.contract;

import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.project.SplitPageInfo;
import org.slf4j.Logger;

import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.model.contract.Contract;
import com.ptswitch.material.model.material.Material;
import com.ptswitch.material.model.security.Role;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.ContractService;
import com.ptswitch.material.service.MaterialService;
import com.ptswitch.material.util.ContractUtil;
import com.ptswitch.material.util.security.PermissionUtil;

//use for search material items
public class AddItems extends PageBase {
    @Inject
    private Logger logger;
    @Inject
    private ContractService contractSer;
    @Inject
    private MaterialService materialSer;
    @Property
    private Contract contract;
    private long id;
    @Property
    private List<Material> list;
    @Property
    private SplitPageInfo page = new SplitPageInfo();
    @Property
    private String like;
    //
    @InjectPage
    private ViewContract viewContract;

    public Object withInit(long id, String like, long size, long first) {
        this.id = id;
        this.like = like;
        page.setPageSize(size);
        page.setCurrentPage(first);
        return this;
    }

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init(long id, String like, long size, long first) {
        withInit(id, like, size, first);
        contract = contractSer.findById(id, ContractService.Init_Items);
        checkPermitted(PermissionUtil.ContractItemAdd);
        if (contract.isContractOk()) {
            setMessage("合同已完成");
            return viewContract.withInit(contract.getId());
        }
        page.setRowCount(materialSer.countLike(like));
        list = materialSer.findLike(like, page.getCurrentRow(), page.getPageSize());
        return null;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return new Object[] { id, like, page.getPageSize(), page.getCurrentPage() };
    }

    //for test
    //here,selectItem is a event name,not a component name!
    //see MaterialForContractRow
    @OnEvent(value = "selectItem")
    Object selectItem() {
        logger.debug("select item");
        return this;
    }

    @Override
    protected List<Role> appendRoleToVisitor(Uzer visitor) {
        return ContractUtil.appendThisRole(contract, visitor);
    }
}
